package com.gack.business.service;

import java.net.URLEncoder;
import java.util.Date;
import java.util.Random;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gack.business.model.BackCode;
import com.gack.business.model.ReturnResult;
import com.gack.business.repository.BackCodeRepository;
import com.gack.helper.common.abstractobj.ApiController;
import com.gack.helper.common.util.SMSHelper;
import com.gack.helper.common.util.StdRandom;
/***
 * 
 * @author zj
 *
 */




@Service
public class BackCodeService {

	
	
	@Autowired
	private  BackCodeRepository  backCodeRepository;
	
	
	
	
	
	/**
	 * 
	* @Description: 发送验证码并且将验证码及用户手机号入库 使用@Transactional处理事务
	* @param telephone 用户手机号
	* @param @throws Exception
	* @return ReturnResult    
	* @throws 
	 */
	@Transactional
    public ReturnResult sendCode(String name,String telephone) throws Exception{
    	ReturnResult returnResult = new ReturnResult();
    	String url = ApiController.SMS_URL;
		String username = ApiController.SMS_USERNAME;
		String password = ApiController.SMS_PASSWORD;
		String epid = ApiController.SMS_EPID;
		String param = "";
		String code="";
	    String sendingcode = "";
		code=getSixCode();
		BackCode  operatorCode=new BackCode();
		if(telephone!=null&&name!=null){
			//保存5分钟后的时间，验证时用now即可
	        long curren = System.currentTimeMillis();
	        curren += 5 * 60 * 1000;
	        Date da = new Date(curren);
	        operatorCode =backCodeRepository.selectByPhoneAndCodetextAndCreatedate(code,telephone,new Date());
	      
			if(null!=operatorCode&&null!=operatorCode.getCodetext()){
				sendingcode = operatorCode.getCodetext();
				operatorCode.setCreatedate(da);
				backCodeRepository.save(operatorCode);
			} else {
				 operatorCode=new BackCode();
			}
		if("".equals(sendingcode)){
			        operatorCode.setCreatedate(da);
			        operatorCode.setPhone(telephone);
			        operatorCode.setCodetext(code);
			        backCodeRepository.save(operatorCode);
			        sendingcode=code;
			}
		}
		param = "username=" + username + "&password=" + password + "&phone=" + telephone + "&epid=" + epid
				+ "&linkid=&subcode=" + "&message=" + URLEncoder.encode("【i商务】尊敬的"+name+"您好，"
						+ "您的验证码为："+sendingcode+"，有效时间五分钟，请您尽快操作。", "gb2312");
		String result = SMSHelper.SendGET(url, param);
		if(result.equals("00")){
    		returnResult.setKey("success");
    		returnResult.setValue(sendingcode);
		}else if(result.equals("2")){
				returnResult.setKey("error");
	    		returnResult.setValue("鉴权失败");
		}else{
				returnResult.setKey("error");
	    		returnResult.setValue("发送失败");
		}
		return returnResult;
    }
	
	
	
	
	
	public ReturnResult sendCodeforAddAccount(String name,String pwd,String telephone,String account) throws Exception{
		ReturnResult returnResult = new ReturnResult();
		String url = ApiController.SMS_URL;
		String username = ApiController.SMS_USERNAME;
		String password = ApiController.SMS_PASSWORD;
		String epid = ApiController.SMS_EPID;
		String param = "";
		String code="";
		code=pwd;
		param = "username=" + username + "&password=" + password + "&phone=" + telephone + "&epid=" + epid
				+ "&linkid=&subcode=" + "&message=" + URLEncoder.encode("【i商务】尊敬的"+name+"您好，公司为您创建了i商务后台账号，"
						+ "账号："+account+",密码为："+code+",请您及时登录进行密码修改。", "gb2312");
		String result = SMSHelper.SendGET(url, param);
		if(result.equals("00")){
			returnResult.setKey("success");
			returnResult.setValue(code);
		}else if(result.equals("2")){
			returnResult.setKey("error");
			returnResult.setValue("鉴权失败");
		}else{
			returnResult.setKey("error");
			returnResult.setValue("发送失败");
		}
		return returnResult;
	}
	
	// 获取6位数字验证码
		public static String getSixCode(){
			StringBuilder code = new StringBuilder();
			Random random = new Random();
			for (int i = 0; i < 6; i++) {
				code.append(String.valueOf(random.nextInt(10)));
			}
			
			String smsText = "" + code;
			return  smsText;
		}
		
		// 获取6位随机数加字母
				public static String getSixCodeforAccount(){
					  //数组，用于存放随机字符
			        char[] chArr = new char[6];
			        //为了保证必须包含数字、大小写字母
			        chArr[0] = (char)('0' + StdRandom.uniform(0,10));
			        chArr[1] = (char)('A' + StdRandom.uniform(0,26));
			        chArr[2] = (char)('a' + StdRandom.uniform(0,26));
			        char[] codes = { '0','1','2','3','4','5','6','7','8','9',
			                         'A','B','C','D','E','F','G','H','I','J',
			                         'K','L','M','N','O','P','Q','R','S','T',
			                         'U','V','W','X','Y','Z','a','b','c','d',
			                         'e','f','g','h','i','j','k','l','m','n',
			                         'o','p','q','r','s','t','u','v','w','x',
			                         'y','z'};
			        //charArr[3..len-1]随机生成codes中的字符
			        for(int i = 3; i < 6; i++){
			            chArr[i] = codes[StdRandom.uniform(0,codes.length)];
			        }
			        
			        //将数组chArr随机排序
			        for(int i = 0; i < 6; i++){
			            int r = i + StdRandom.uniform(6 - i);
			            char temp = chArr[i];
			            chArr[i] = chArr[r];
			            chArr[r] = temp;
			        }
			        
			        StringBuffer sb = new StringBuffer();
			        for(int i = 0; i < chArr.length; i++)
			        { 
			        sb. append(chArr[i]);
			        }
			        String s = sb.toString();
			        
			        return s;
				}
	
	
	
}
